package com.banciyuan.bcywebview.biz.search;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.baidu.mobstat.StatService;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.EventApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.base.view.tag.TagView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.event.EventDetailActivity;
import com.banciyuan.bcywebview.utils.constants.EventConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.daoexample.model.Event;
import de.greenrobot.daoexample.model.TagDetail;

public class SearchActivity extends BaseActivity implements View.OnClickListener, TextView.OnEditorActionListener, BaseWatcher {

    public static final int TAG = 0;
    private EditText mContentEt;
    private ImageView mDeleteImg;
    private TextView mCancelTv;
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private RequestQueue queue;

    private View llMainContainer;
    private View llHistorySearch;
    private View llEventSearch;
    private View llLikeSearch;
    private View llGroupSearch;
    private TextView clearHistory;

    private TagView historyTags;
    private TagView eventTags;
    private TagView likeTags;
    private TagView groupTags;

    private List<String> historyList = new ArrayList<>();

    private LinearLayout llResult;
    private LinearLayout llContent;
    private SearchInnerFragment searchInnerFragment;
    private SearchAutoFragment searchAutoFragment;

    private FragmentManager fm;
    private String type = "all";
    private String name;
    private List<TagDetail> mHotSearchTags;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.discover_search_layout);
        initArgs();
        initProgressbar();
        getFragment();
        initUi();
        initHistoryData();
        if (type.equals("all")) {
            processHotSearchData();
            processHotSearchSingleData();
            initEventData();
        } else if (type.equals("group")) {
            processHotSearchGroupData();
            processHotSearchGroupSingleData();
        }
        initAction();
    }

    private void getFragment() {
        searchInnerFragment = new SearchInnerFragment();
        searchAutoFragment = new SearchAutoFragment();
        addFragment();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }

    private void initHistoryData() {
        String result = SPHelper.getString(this, SPConstant.BCY_LASTSEARCH, SPConstant.BCY_LASTSEARCH, "[]");
        Gson gson = new Gson();
        historyList = gson.fromJson(result, new TypeToken<List<String>>() {
        }.getType());
        processHistoryData();
    }

    private void initEventData() {
        List<BcyPair> paramsList = new ArrayList<>();
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + EventApi.getHotSearch();
        Response.Listener onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject result = new JSONObject(s);
                    String status = result.getString(HttpUtils.UPLOAD_STATUS);
                    if (status.equals("1")) {
                        Gson gson = new Gson();
                        List<Event> events = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<Event>>() {
                        }.getType());
                        processEventData(events);
                        mProgressbarHelper.onSuccess();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSucc, errorProxy);
        queue.add(stringRequest);
    }

    private void processHotSearchGroupSingleData() {
        if (mHotSearchTags != null && !mHotSearchTags.isEmpty()) {
            String hotTag = mHotSearchTags.get(0).getTag_name();
            if (!TextUtils.isEmpty(hotTag))
                mContentEt.setHint(String.format(getString(R.string.search_hotgroup_content_format), hotTag));
            else
                mContentEt.setHint(getString(R.string.search_your_interest));
        } else {
            mContentEt.setHint(getString(R.string.search_your_interest));
        }
    }

    private void processHotSearchGroupData() {
        if (mHotSearchTags != null && !mHotSearchTags.isEmpty()) {
            groupTags.setTlist(mHotSearchTags);
            groupTags.setTagViewClick(new TagView.OnTagClickListener() {
                @Override
                public void onClick(TagDetail t) {
                    showResultFragment(t.getTag_name(), 6);
                }
            });
            llGroupSearch.setVisibility(View.VISIBLE);
        } else {
            llGroupSearch.setVisibility(View.GONE);
        }
    }

    private void processEventData(List<Event> events) {
        if (events != null && !events.isEmpty()) {
            List<TagDetail> tlist = new ArrayList<>();
            for (int i = 0; i < events.size(); i++) {
                TagDetail tagdetail = new TagDetail();
                tagdetail.setTag_name(events.get(i).getTag_name());
                tagdetail.setEvent_id(events.get(i).getEvent_id());
                tlist.add(tagdetail);
            }
            eventTags.setTlist(tlist);
            eventTags.setTagViewClick(new TagView.OnTagClickListener() {
                @Override
                public void onClick(TagDetail t) {
                    gotoUtil.gotoAct(SearchActivity.this, EventDetailActivity.class, t.getEvent_id());
                }
            });
            llEventSearch.setVisibility(View.VISIBLE);
        } else {
            llEventSearch.setVisibility(View.GONE);
        }
    }

    private void processHotSearchData() {
        if (mHotSearchTags != null && !mHotSearchTags.isEmpty()) {
            likeTags.setTlist(mHotSearchTags);
            likeTags.setTagViewClick(new TagView.OnTagClickListener() {
                @Override
                public void onClick(TagDetail t) {
                    showResultFragment(t.getTag_name(), 0);
                }
            });
            llLikeSearch.setVisibility(View.VISIBLE);
        } else {
            llLikeSearch.setVisibility(View.GONE);
        }
    }

    private void processHotSearchSingleData() {
        if (mHotSearchTags != null && !mHotSearchTags.isEmpty()) {
            String hotTag = mHotSearchTags.get(0).getTag_name();
            if (!TextUtils.isEmpty(hotTag))
                mContentEt.setHint(String.format(getString(R.string.search_hot_content_format), hotTag));
            else
                mContentEt.setHint(getString(R.string.search_your_interest_circle));
        } else {
            mContentEt.setHint(getString(R.string.search_your_interest_circle));
        }
    }

    private void processHistoryData() {
        if (historyList != null && !historyList.isEmpty()) {
            List<TagDetail> tlist = new ArrayList<>();
            for (int i = 0; i < historyList.size(); i++) {
                TagDetail tagdetail = new TagDetail();
                tagdetail.setTag_name(historyList.get(i));
                tlist.add(tagdetail);
            }
            historyTags.setTlist(tlist);
            historyTags.setTagViewClick(new TagView.OnTagClickListener() {
                @Override
                public void onClick(TagDetail t) {
                    if (type.equals("all")) {
                        showResultFragment(t.getTag_name(), 0);
                    } else if (type.equals("goods")) {
                        showResultFragment(t.getTag_name(), 5);
                    } else if (type.equals("group")) {
                        showResultFragment(t.getTag_name(), 6);
                    } else {
                        showResultFragment(t.getTag_name(), 0);
                    }
                }
            });
            llHistorySearch.setVisibility(View.VISIBLE);
        } else {
            llHistorySearch.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initArgs() {
        fm = getSupportFragmentManager();
        queue = VolleyQueue.getRquest(this);
        Intent intent = getIntent();
        type = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        mHotSearchTags = (List<TagDetail>) intent.getSerializableExtra(gotoUtil.INTENT_VALUE_TWO);
        name = intent.getStringExtra(gotoUtil.INTENT_VALUE_THREE);
        if (TextUtils.isEmpty(type)) type = "all";
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
    }

    @Override
    protected void initUi() {
        mContentEt = (EditText) findViewById(R.id.discover_search_commentcontent_et);
        mDeleteImg = (ImageView) findViewById(R.id.discover_search_delete_img);
        mCancelTv = (TextView) findViewById(R.id.discover_search_cancel_tv);
        llResult = (LinearLayout) findViewById(R.id.search_fragment_container);
        llContent = (LinearLayout) findViewById(R.id.search_fragment_result_container);
        llMainContainer = findViewById(R.id.ll_main_search);
        llMainContainer.setVisibility(View.VISIBLE);

        llHistorySearch = findViewById(R.id.history_ll);
        llEventSearch = findViewById(R.id.event_ll);
        llLikeSearch = findViewById(R.id.like_ll);
        llGroupSearch = findViewById(R.id.group_ll);
        historyTags = (TagView) findViewById(R.id.history_tag);
        eventTags = (TagView) findViewById(R.id.event_tag);
        likeTags = (TagView) findViewById(R.id.likes_tag);
        groupTags = (TagView) findViewById(R.id.group_tags);

        clearHistory = (TextView) findViewById(R.id.clear_history);

        llMainContainer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                hideSoftKeyboard();
                return true;
            }
        });

    }

    @Override
    protected void initAction() {
        mDeleteImg.setOnClickListener(this);
        mCancelTv.setOnClickListener(this);
        clearHistory.setOnClickListener(this);
        mContentEt.setOnEditorActionListener(this);
        mContentEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString().trim())) {
                    mDeleteImg.setVisibility(View.VISIBLE);
                    showAutoFragment();
                } else {
                    llResult.setVisibility(View.GONE);
                    mDeleteImg.setVisibility(View.GONE);
                    Bundle bundle = new Bundle();
                    bundle.putString("query", "");
                    searchAutoFragment.setArguments(bundle);
                }
            }
        });

    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        switch (actionId) {
            case EditorInfo.IME_ACTION_SEARCH:
                String query = mContentEt.getText().toString();
                query = checkDefaultQuery(query);
                if (!TextUtils.isEmpty(query)) {
                    if (type.equals("all")) {
                        showResultFragment(query, 0);
                    } else if (type.equals("goods")) {
                        showResultFragment(query, 5);
                    } else if (type.equals("group")) {
                        showResultFragment(query, 6);
                    } else {
                        showResultFragment(query, 0);
                    }
                    hideSoftKeyboard();
                } else {
                    MyToast.show(this, getString(R.string.input_empty_content));
                }
                break;

            default:
                break;
        }
        return true;
    }

    @Nullable
    private String checkDefaultQuery(String query) {
        if ("all".equals(type)) {
            if (TextUtils.isEmpty(query)) {
                String hint = mContentEt.getHint().toString();
                if (hint.startsWith(getString(R.string.search_hot_content))) {
                    query = hint.substring(getString(R.string.search_hot_content).length(), hint.length());
                }
            }
        } else if ("group".equals(type)) {
            if (TextUtils.isEmpty(query)) {
                String hint = mContentEt.getHint().toString();
                String groupStartHint = getString(R.string.search_hotgroup_content_start);
                String groupEndHint = getString(R.string.search_hotgroup_content_end);
                String pattern = "^" + groupStartHint + "(.+)" + groupEndHint + "$";
                Pattern r = Pattern.compile(pattern);
                Matcher matcher = r.matcher(hint);
                if (matcher.find()) {
                    query = matcher.group(1);
                }
            }
        }
        return query;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.clear_history:
                historyTags.reset();
                SPHelper.putString(this, SPConstant.BCY_LASTSEARCH, SPConstant.BCY_LASTSEARCH, "[]");
                llHistorySearch.setVisibility(View.GONE);
                break;
            case R.id.discover_search_delete_img:
                mContentEt.setText("");
                mDeleteImg.setVisibility(View.INVISIBLE);
                showSoftInput();
                break;
            case R.id.discover_search_cancel_tv:
                finish();
                break;
            default:
                break;
        }
    }

    public void hideSoftKeyboard() {
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (null != inputManager && inputManager.isActive()) {
            inputManager.hideSoftInputFromWindow(mContentEt.getApplicationWindowToken(), 0);
        }
    }

    public void showSoftInput() {
        InputMethodManager inputManager = (InputMethodManager)
                mContentEt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (null != inputManager && inputManager.isActive()) {
            inputManager.showSoftInputFromInputMethod(mContentEt.getWindowToken(), 0);
            inputManager.toggleSoftInput(0, 0);
        }
    }

    private void addHistory(String query) {
        if (historyList != null && historyList.size() < 10) {
            if (!historyList.contains(query)) {
                historyList.add(0, query);
            }
        } else if (historyList != null && historyList.size() >= 10) {
            if (!historyList.contains(query)) {
                historyList.add(0, query);
                historyList.remove(historyList.size() - 1);
            }
        }
        Gson gson = new Gson();
        SPHelper.putString(this, SPConstant.BCY_LASTSEARCH, SPConstant.BCY_LASTSEARCH, gson.toJson(historyList));
    }

    public void showResultFragment(String query, int select) {
        StatService.onEvent(this, EventConstants.SEARCH, EventConstants.SEARCH_EVENT);
        addHistory(query);
        if (StringUtil.notNullEqual(type, "circle") && !TextUtils.isEmpty(name)) {
            query = name + " " + query;
        }
        mContentEt.setText(Html.fromHtml(query));
        llContent.setVisibility(View.VISIBLE);
        llResult.setVisibility(View.GONE);
        Bundle bundle = new Bundle();
        bundle.putString("query", query);
        bundle.putInt("select", select);
        bundle.putString("filter", type);
        if (searchInnerFragment != null && !isFinishing()) {
            searchInnerFragment.setInit(bundle);
        }
        hideSoftKeyboard();
    }

    private void showAutoFragment() {
        llResult.setVisibility(View.VISIBLE);
        Bundle bundle = new Bundle();
        bundle.putString("query", mContentEt.getText().toString());
        searchAutoFragment.setArguments(bundle);
    }

    private void addFragment() {
        if (!searchAutoFragment.isAdded()) {
            android.support.v4.app.FragmentTransaction fts = fm.beginTransaction();
            fts.add(R.id.search_fragment_container, searchAutoFragment, "AUTO");
            fts.show(searchAutoFragment);
            fts.commit();
        }

        if (!searchInnerFragment.isAdded()) {
            FragmentTransaction fts2 = fm.beginTransaction();
            fts2.add(R.id.search_fragment_result_container, searchInnerFragment, "Inner");
            fts2.show(searchInnerFragment);
            fts2.commit();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseObserver.getInstance().addWatcher(SearchActivity.class, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BaseObserver.getInstance().removeWatcher(SearchActivity.class);
    }

    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        switch (eventCode) {
            case BaseObserver.SEARCH_GOTO_USER:
                if (searchInnerFragment != null && !isFinishing()) {
                    searchInnerFragment.gotoIndex(SearchInnerFragment.PERSONINDEX);
                }
                break;
        }
    }

}